package commands;

import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

import main.InputHandler;
import util.*;

public class OpenPortCommand extends Command {
	public static String name = "openport";
	public static String help = "Name: openport \n>openport {int:form('0####')} \n>openport (portnumber) \n>Command to open a server socket on the specified port.";
	public static ServerSocket serverSocket;
	public static HashMap<String, ConnectionData> sockets = new HashMap<String, ConnectionData>();
	public static boolean opened = false;
	
	public static boolean test(InputHandler handler, StringList words){
		if(StringChecker.testWord(words, 0, "openport")){
			if(StringChecker.testFormat(words, 1, "0####")){
				if(!opened){
					try {
						opened = true;
						serverSocket = new ServerSocket(Integer.parseInt(words.get(1)));
						Thread connectThread = new Thread(){
							public void run(){
								while(true){
									try {
										ConnectionData temp = new ConnectionData(serverSocket.accept());
										String name;
										while((name = (String)temp.read()) == null){
											Thread.sleep(50);
										}
										sockets.put(name, temp);
									} catch (Exception e){}
								}
							}
						};
						connectThread.start();
						handler.terminal.write("Port created");
						return true;
					} catch (Exception e){
						handler.terminal.write("Couldn't open connection on specified port");
						return true;
					}
				}
				handler.terminal.write("Already opened a socket");
				return true;
			}
			handler.terminal.write("Invalid port");
			return true;
		}
		return false;
	}
	
	public static Collection<ConnectionData> getSockets(){
		return sockets.values();
	}
	
	public static Set<String> getKeys(){
		return sockets.keySet();
	}

}
